iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
佛心分享-刷題不只是刷題

轉生理工組後從零開始的leetcode刷題系列 第 4

day-4[easy.1812]determine color of a chessboard square

  • 分享至 

  • xImage
  •  

You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
https://ithelp.ithome.com.tw/upload/images/20240918/20169432B2Q8ER1BtG.png
Return true if the square is white, and false if the square is black.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.


難得有一個我看得懂英文的題目!
大意是題目會給我們一個位置(英文+數字),我們需要判斷它是黑色還是白色。
https://ithelp.ithome.com.tw/upload/images/20240918/20169432cNr4UgEKB1.jpg
這題在思考規律的部分會花比較多時間,
我一開始是拆成英文和數字兩個部分,先判斷英文奇偶再判斷數字奇偶,
但畫完樹狀圖才想到其實可以直接把兩個部分相加後判斷奇偶,這樣程式會簡潔非常多!


努力的結晶:
public class Solution {
public static int abcToNumber(char abc){
switch (abc){
case 'a': return 1;
case 'b': return 2;
case 'c': return 3;
case 'd': return 4;
case 'e': return 5;
case 'f': return 6;
case 'g': return 7;
case 'h': return 8;
default: return 0;
}
}

public static boolean white(String coordinates) {
    int abc = abcToNumber(coordinates.charAt(0));
    int number = Character.getNumericValue(coordinates.charAt(1));
    return (abc + number) % 2 != 0;

}

}
https://ithelp.ithome.com.tw/upload/images/20240918/20169432GpjGQMvYOX.png
結果錯在一個超好笑的地方,
我的布林值沒有依照題目要求的方式命名,所以沒辦法run
很普通的修改名稱後結束這回合!!
https://ithelp.ithome.com.tw/upload/images/20240918/2016943291uj495Q7k.png


上一篇
day-3[easy.2047]number of valid words in a sentence
下一篇
day-5[easy.1913]maximum product difference between two pairs
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言